package com.tisson.dict.pingserver.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

import java.time.Instant;
import java.util.concurrent.atomic.AtomicLong;

@RestController
@RequestMapping("/pong")
public class PongController {
    private final AtomicLong lastProcessedSecond = new AtomicLong(0);

    @PostMapping("/answer")
    public Mono<ResponseEntity<String>> answer() {
        long currentSecond = Instant.now().getEpochSecond();
        long lastSecond = lastProcessedSecond.getAndUpdate(
                prev -> (currentSecond != prev) ? currentSecond : prev
        );

        if (currentSecond == lastSecond) {
            return Mono.just(ResponseEntity.status(429).body("Too Many Requests"));
        }

        return Mono.just(ResponseEntity.ok("World"));
    }

}
